package com.oriole.oauth2.server.config;

import com.oriole.common.constant.ResultModel;
import com.oriole.entity.security.OrioleUserDetails;
import com.oriole.entity.sys.SysRole;
import com.oriole.entity.sys.SysUser;
import com.oriole.oauth2.server.feign.ISysUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelife
 * Date: 2020/8/2 19:00
 * description: 自定义加载用户数据
 */
@Component
public class OrioleUserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private ISysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ResultModel<SysUser> rmSysUser = sysUserService.findByUsername(username);
        SysUser sysUser = rmSysUser.getData();
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        Set<SysRole> sysRoles = sysUser.getSysRoles();
        sysRoles.forEach(sysRole -> {
            SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysRole.getName());
            grantedAuthorities.add(grantedAuthority);
        });
        return new OrioleUserDetails(sysUser.getUsername(), sysUser.getPassword(), grantedAuthorities, sysUser.getId(), sysUser.getSysDept().getId());
    }
}
